package com.vitalfit.strategy.strategyImpl;


import com.vitalfit.exception.UserNotFoundException;
import com.vitalfit.handler.HandlerChainManager;
import com.vitalfit.handler.handlerImpl.CustomerHandler;
import com.vitalfit.model.dto.HandleDTO;
import com.vitalfit.model.entity.user.Customer;
import com.vitalfit.repository.UserRepository;
import com.vitalfit.strategy.UserStrategy;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RequiredArgsConstructor
public class EditCustomerStrategy implements UserStrategy {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public Object execute(HandleDTO handleDTO) {

        Customer customer = (Customer) userRepository.findById(handleDTO.getId()).orElseThrow(
                () -> new UserNotFoundException("User not found")
        );

        HandlerChainManager<Customer> handlerChainManager = new HandlerChainManager<>();
        handlerChainManager.addHandler(new CustomerHandler(passwordEncoder));
        handlerChainManager.handle(customer, handleDTO);

        return userRepository.save(customer);

    }
}
